import type {ErrorMessageMode, UserInfo} from '@pkg/types';
import type {GetUserInfoModel, LoginParams} from '@pkg/apis/sys';
import {doLogout, getUserInfo, initDict, loginApi, thirdLogin, ThirdLoginParams} from '@pkg/apis/sys';
import {defineStore} from 'pinia';
import {PageEnum, RoleEnum} from '@pkg/tokens';
import {isArray} from '@pkg/utils';
import {useI18n} from '@pkg/locale';
import {pinia} from '@/internal';
import {useMessage} from '@/hooks/web/useMessage';
import {router} from '@/router';
import {usePermissionStore} from '@/store/permission';
import {PAGE_NOT_FOUND_ROUTE} from '@/router/routes/basic';
import {h} from 'vue';
import {Modal} from "ant-design-vue";

interface UserState {
  userInfo: Nullable<UserInfo>;
  token?: string;
  roleList: RoleEnum[];
  dictData: any[];
  sessionTimeout?: boolean;
  lastUpdateTime: number;
}

//定义用户Store
export const useUserStore = defineStore({
  id: 'app-user',
  persist: {
    strategies: [
      {
        //需要缓存键
        paths: ['userInfo', 'token', 'roleList', 'dictData'],
      },
    ],
  },
  state: (): UserState => ({
    // 用户信息
    userInfo: null,
    // token
    token: undefined,
    // 角色列表
    roleList: [],
    // 字典
    dictData: [],
    //登录是否过期
    sessionTimeout: false,
    //上次更新时间
    lastUpdateTime: 0,
  }),
  getters: {
    getUserInfo(): UserInfo {
      return this.userInfo || ({} as UserInfo);
    },
    isSuperAdmin(): boolean {
      return this.getUserInfo.superAdmin==1;
    },
    getToken(): string {
      return this.token as string;
    },
    getRoleList(): RoleEnum[] {
      return this.roleList.length > 0 ? this.roleList : [];
    },
    getSessionTimeout(): boolean {
      return !!this.sessionTimeout;
    },
    getLastUpdateTime(): number {
      return this.lastUpdateTime;
    },
    getDictData(): any[] {
      return this.dictData;
    },
  },
  actions: {
    setToken(info: string | undefined) {
      // for null or undefined value
      this.token = info ? info : '';
    },
    setRoleList(roleList: RoleEnum[]) {
      this.roleList = roleList;
    },
    setUserInfo(info: UserInfo | null) {
      this.userInfo = info;
      this.lastUpdateTime = new Date().getTime();
    },
    setSessionTimeout(flag: boolean) {
      this.sessionTimeout = flag;
    },
    setDictData(dictData: any[]) {
      this.dictData = dictData;
    },
    resetState() {
      this.userInfo = null;
      this.token = '';
      this.roleList = [];
      this.sessionTimeout = false;
    },
    /**
     * 登录
     */
    async login(
      params: LoginParams & {
        goHome?: boolean;
        mode?: ErrorMessageMode;
      },
    ): Promise<GetUserInfoModel | null> {
      try {
        const { goHome = true, mode, ...loginParams } = params;

        const data = await loginApi(loginParams, mode);
        if(data.access_token)
        {
          const { access_token } = data;
          // 保存token
          this.setToken(access_token);
          return this.afterLoginAction(goHome);
        }

      } catch (error) {
        //return Promise.reject(error);
      }
    },
    /**
     * 登录
     */
    async thirdLogin(
      params: ThirdLoginParams & {
        goHome?: boolean;
        mode?: ErrorMessageMode;
      },
    ): Promise<GetUserInfoModel | null> {
      try {
        const { goHome = true, mode, ...thirdLoginParams } = params;

        const data = await thirdLogin(thirdLoginParams, mode);
        if(data.access_token)
        {
          const { access_token } = data;

          // 保存token
          this.setToken(access_token);
          return this.afterLoginAction(goHome);
        }

      } catch (error) {
        alert(3);
        return Promise.reject(error);
      }
    },
    //登录后处理
    async afterLoginAction(goHome?: boolean,data?: any): Promise<GetUserInfoModel | null> {
      if (!this.getToken) {
        return null;
      }
      // 获取用户信息
      const userInfo = await this.getUserInfoAction();

      const sessionTimeout = this.sessionTimeout;
      if (sessionTimeout) {
        this.setSessionTimeout(false);
      } else {
        const permissionStore = usePermissionStore();
        let homePath=PageEnum.WORKBENCH;
        if (!permissionStore.isDynamicAddedRoute) {
          const routes:any = await permissionStore.buildRoutesAction();
          routes.forEach((route:any) => {
            router.addRoute(route);
          });
          routes[1].children.forEach((item)=>{
            if(item.path.indexOf("analysis")>-1){
              homePath=PageEnum.WORKBENCH;
            }
          })
          router.addRoute(PAGE_NOT_FOUND_ROUTE);
          permissionStore.setDynamicAddedRoute(true);
        }
        goHome && (await router.replace(userInfo?.homePath || homePath));
      }
      return userInfo;
    },
    //获取用户信息
    async getUserInfoAction(): Promise<UserInfo | null> {
      if (!this.getToken) {
        return null;
      }

      const userInfo = await getUserInfo();
      const { roles = [] }:any = userInfo.attrs;
      if (isArray(roles)) {
        const roleList = roles.map((item) => item) as RoleEnum[];
        this.setRoleList(roleList);
      } else {
        userInfo.roles = [];
        this.setRoleList([]);
      }
      this.setUserInfo(userInfo);
      return userInfo;
    },
    /**
     * 退出登录
     */
    async logout(goLogin = false) {
      if (this.getToken) {
        await doLogout().catch(() => {
          console.log('注销Token失败');
        });
      }
      this.setToken(undefined);
      this.setSessionTimeout(false);
      this.setUserInfo(null);
      goLogin && (await router.push(PageEnum.BASE_LOGIN));
    },

    /**
     * 退出登录询问
     */
    confirmLoginOut() {
      const { createConfirm } = useMessage();
      const { t } = useI18n();
      createConfirm({
        iconType: 'warning',
        title: () => h('span', t('sys.app.logoutTip')),
        content: () => h('span', t('sys.app.logoutMessage')),
        onOk: async () => {
          await this.logout(true);
        },
      });
    },

    /**
     * 初始化系统字典
     */
    async initDictAction() {
      await initDict()
        .then((data) => {
          this.setDictData(data);
        })
        .catch(() => {
          console.log('初始化字典失败');
        });
    },
  },
});

// 需要在设置之外使用
export function useUserStoreWithOut() {
  return useUserStore(pinia);
}
